﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Oplug.Services
{
    public class UtilityService
    {
        public static T MapTo<T>(object type)
        {
            string jsonText = JsonConvert.SerializeObject(type);
            T obj = JsonConvert.DeserializeObject<T>(jsonText);
            return obj;
        }

        public static DataTable ExecuteSQL(DbContext db, string sql, params System.Data.Common.DbParameter[] parameters)
        {
            DataTable dt = new DataTable();

            var conn = db.Database.Connection;
            conn.Open();
            using (var cmd = db.Database.Connection.CreateCommand())
            {
                foreach (var p in parameters) cmd.Parameters.Add(p);

                cmd.CommandText = sql;
                dt.Load(cmd.ExecuteReader());
            }
            conn.Close();

            return dt;
        }

        public static string CStr(object val)
        {
            try
            {
                return val.ToString();
            }
            catch { return ""; }
        }
        public static decimal CDec(object val)
        {
            try
            {
                return Convert.ToDecimal(val);
            }
            catch { return 0; }
        }
        public static double CDoub(object val)
        {
            try
            {
                return Convert.ToDouble(val);
            }
            catch { return 0; }
        }
        public static int CInt(object val)
        {
            try
            {
                return Convert.ToInt32(val);
            }
            catch { return 0; }
        }
        public static DateTime CDate(object val)
        {
            try
            {
                return Convert.ToDateTime(val);
            }
            catch { return DateTime.Now; }
        }


    }
}
